package com.guowei.web.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class WindowsPathUtil implements PathUtil {

    @Override
    public String uri2Path(String requestURI) {
        String path = requestURI.substring(1);
        int indexOf = path.indexOf("/");
        path = path.substring(0, indexOf) + ":" + path.substring(indexOf);
        return path;
    }

    @Override
    public String path2Uri(String path) {
        try {
            StringBuilder uri = new StringBuilder("/");
            StringBuilder fileName = new StringBuilder();
            for (int i = 0; i < path.length(); i++) {
                char c = path.charAt(i);
                if (c == ':') {
                    if (i + 2 == path.length()) {
                        i++;
                    }
                    continue;
                } else if (c == '\\' || c == '/') {
                    if (fileName.length() > 0) {
                        uri.append(URLEncoder.encode(fileName.toString(), StandardCharsets.UTF_8.name()));
                        uri.append("/");
                        fileName.setLength(0);
                    }
                } else {
                    fileName.append(c);
                }
            }
            if (fileName.length() > 0) {
                uri.append(URLEncoder.encode(fileName.toString(), StandardCharsets.UTF_8.name()));
                uri.append("/");
            }
            return uri.toString();
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}
